package com.huicoo.forestmanager.widget.update;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;

import com.huicoo.forestmanager.util.LogUtils;

import java.io.File;

public class DownManager implements DownListener, DownDialog.DownDialogListener {
    public static final String TAG = "AppDownloadManager";
    public static final String SPLIT_STR = "%-----%";   //乐橙用 分割符

    private AppCompatActivity activity;
    private Context context;
    private AppUpdateDialog appUpdateDialog;
    private DownDialog downDialog;
    private DownUtil downUtil;
    private boolean isForce;
    private String downloadPath;
    private OnPermissionListener onPermissionListener;

    public DownManager(AppCompatActivity activity) {
        this.context = activity.getApplicationContext();
        this.activity = activity;
        appUpdateDialog = new AppUpdateDialog(activity);
        downDialog = new DownDialog(activity);
        downDialog.setOnDialogClickListener(this);
        downUtil = new DownUtil(this);

        appUpdateDialog.setOnAppUpdateListener(new AppUpdateDialog.OnAppUpdateListener() {
            @Override
            public void toUpdate(String downloadUrl) {
                toDownload(downloadUrl, downloadPath);
                appUpdateDialog.dismiss();
            }
        });
    }

    public static final int DOWN_START = 0;
    public static final int DOWN_PROGRESS = DOWN_START + 1;
    public static final int DOWN_SUCCESS = DOWN_PROGRESS + 1;
    public static final int DOWN_FAILED = DOWN_SUCCESS + 1;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case DOWN_START:
                    downDialog.updateView(0, "准备下载", 0);
                    break;
                case DOWN_PROGRESS:
                    int progress = msg.arg1;
                    long speed = (long) msg.obj;
                    downDialog.updateView(progress, "下载中", speed);
                    break;
                case DOWN_SUCCESS:
                    downDialog.updateView(100, "下载完成，等待安装", 0);
                    dealInstallApk();
                    break;
                case DOWN_FAILED:
                    downDialog.updateView(0, "下载异常", 0);
                    break;
            }
        }
    };

    /***
     * 开始下载
     */

    public void toDownload(String downUrl, String downPath) {
        boolean isGaintedPermission = false;
        if (Build.VERSION.SDK_INT >= 23) {
            try {
                //检测是否有写的权限
                int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    // 没有写的权限，去申请写的权限
                    if (onPermissionListener != null) {
                        onPermissionListener.noPermission();
                    }
                } else {
                    isGaintedPermission = true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            isGaintedPermission = true;
        }
        LogUtils.v("gogogo is Gainted = " + isGaintedPermission);
        if (isGaintedPermission) {
            downDialog.show();
            downUtil.downFile(downUrl, downPath);
        }
    }

    @Override
    public void downStart() {
        handler.sendEmptyMessage(DOWN_START);
    }

    @Override
    public void downProgress(int progress, long speed) {
        Message msg = new Message();
        msg.what = DOWN_PROGRESS;
        msg.arg1 = progress;
        msg.obj = speed;
        handler.sendMessage(msg);
    }

    @Override
    public void downSuccess(String downUrl) {
        handler.sendEmptyMessage(DOWN_SUCCESS);
    }

    @Override
    public void downFailed(String failedDesc) {
        handler.sendEmptyMessage(DOWN_FAILED);
    }

    @Override
    public void noSure() {
        downUtil.cancelDown();
        if (isForce) {
            showAppUpdateDialog();
        }
    }

    public void setDownInfo(AppUpdateDownInfo info, String downloadPath, boolean isForce) {
        this.downloadPath = downloadPath;
        this.isForce = isForce;
        appUpdateDialog.setUpdateInfo(info, isForce);
    }

    public void showAppUpdateDialog() {
        if (appUpdateDialog != null) {
            appUpdateDialog.showDialog();
        }
    }

    private void dealInstallApk() {
        LogUtils.v("gogogo 收到安装apk广播");
        Uri uri;
        Intent intentInstall = new Intent();
        intentInstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intentInstall.setAction(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) { // 6.0以下
            uri = Uri.fromFile(new File(downloadPath));
        } else { // Android 7.0 以上
            uri = FileProvider.getUriForFile(context,
                    context.getPackageName() + ".fileProvider", new File(downloadPath));
            intentInstall.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }

        // 安装应用
        LogUtils.v("gogogo 下载完成了");

        intentInstall.setDataAndType(uri, "application/vnd.android.package-archive");
        context.startActivity(intentInstall);
    }

    public interface OnPermissionListener {
        void noPermission();
    }

    public void setOnPermissionListener(OnPermissionListener onPermissionListener) {
        this.onPermissionListener = onPermissionListener;
    }


}
